package com.hubiao.basics.Transient;

import lombok.Data;

import java.io.*;

/**
 * Description
 *
 * @author hubiao
 * @since 2021-01-16 20:26
 */
public class TransientTest {

    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setUsername( "Java技术栈" );
        user.setId( "javastack" );
        User.setSex( "男" );
        System.out.println( "\n序列化之前" );
        System.out.println( "username: " + user.getUsername() );
        System.out.println( "id: " + user.getId() );

        //进行序列号写入磁盘文件中
        ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream( "d:/user.txt" ) );
        os.writeObject( user );
        os.flush();
        os.close();
        //从磁盘文件中反序列化
        ObjectInputStream is = new ObjectInputStream( new FileInputStream( "d:/user.txt" ) );
        user = (User) is.readObject();
        is.close();
        //将static静态的变量赋值看取出的是内存中的还是反序列化
        User.setSex( "女" );
        System.out.println( "\n序列化之后" );
        System.out.println( "username: " + user.getUsername() );
        System.out.println( "id: " + user.getId() );
        //结果： 女
        System.out.println( "sex: " + User.getSex() );
    }
}

@Data
class User implements Serializable {

    private static final long serialVersionUID = 1L;
    private static String sex;
    private String username;
    private transient String id;

    public static String getSex() {
        return sex;
    }

    public static void setSex(String sex) {
        User.sex = sex;
    }
}
